package com.yfp.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.referencing.GeodeticCalculator;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.referencing.operation.TransformException;

/**
 * GeoTools 是一个强大的开源GIS（地理信息系统）工具包
 * <p>
 * 对GeoTools常用工具进行封装，方便使用
 */
@Slf4j
public class GeoUtils {

    /**
     * 计算两个经纬度之间的距离
     *
     * @param lat1 纬度1
     * @param lon1 经度1
     * @param lat2 纬度2
     * @param lon2 经度3
     * @return 距离
     */
    public static Double calculateDistance(double lat1, double lon1, double lat2, double lon2) {

        log.info("计算经纬度:" + lat1 + "," + lon1 + "," + lat2 + "," + lon2);
        GeodeticCalculator calculator = new GeodeticCalculator();
        DirectPosition2D pos1 = new DirectPosition2D(DefaultGeographicCRS.WGS84, lon1, lat1);
        DirectPosition2D pos2 = new DirectPosition2D(DefaultGeographicCRS.WGS84, lon2, lat2);
        try {
            calculator.setStartingPosition(pos1);
            calculator.setDestinationPosition(pos2);
        } catch (TransformException e) {
            log.error("计算经纬度失败：" + e);
            return null;
        }
        // 返回距离，单位：米
        return calculator.getOrthodromicDistance();
    }
}
